package com.suyl.candy.weather.core.interceptor;

import com.suyl.candy.weather.utils.JWTUtils;
import com.suyl.candy.weather.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    // 访问controller 之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //token验证
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = JWTUtils.parseJWT(token);
            if (claims != null) {
                //账户操作...
                String subject = claims.getSubject();
                Boolean result = true;
                try {
                    Object object = redisUtil.getBoundHashOps("users", subject);
                    if (object != null) {
                        Claims claims1 = JWTUtils.parseJWT(object.toString());
                        Date expiration = claims1.getExpiration();
                        result = expiration.getTime() > System.currentTimeMillis() ? true : false;
                    } else {
                        result = false;
                    }
                } catch (Exception e) {
                    log.error("验证错误" + e.getMessage());
                    result = false;
                } finally {

                }
                return result;
            } else {
                //验证错误,跳转到错误页面
                response.sendRedirect(request.getContextPath() + "/twjd/error");
                return false;
            }
        }
        return false;
    }

    //访问controller之后 访问视图之前被调用

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    //访问视图之后被调用

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
